# worker.py
import asyncio
from app.core.rabbitmq import get_rabbit_channel
import aio_pika
import json

async def process_message(message: aio_pika.IncomingMessage):
    async with message.process():  # 自动 ack/nack
        try:
            body = message.body.decode()
            data = json.loads(body)
            print(f"📩 Received: {data}")

            # 模拟耗时任务
            await asyncio.sleep(2)

            print(f"✅ Processed: {data['message']}")
        except Exception as e:
            print(f"❌ Error processing message: {e}")
            # 抛出异常会自动 nack（如果未使用 process() 上下文）

async def start_consumer():
    channel = await get_rabbit_channel()
    exchange = await channel.declare_exchange("main_exchange", "topic")
    # 声明队列（持久化）
    queue = await channel.declare_queue(
        "task_queue",
        durable=True,
        exclusive=False,
        auto_delete=False
    )
    await queue.bind(exchange, routing_key="task_queue")

    print("📦 消费端已启动，等待消息...")

    # 开始监听
    try:
        await queue.consume(process_message)
    except asyncio.CancelledError:
        print("🛑 消费端被取消.")
        # 可以在这里关闭 channel 或清理资源
        raise  # 重新抛出，让外层处理